package com.rede.didiok.admin.support;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.gson.internal.LinkedTreeMap;
import com.rede.didiok.admin.config.BaiduSeoConfig;
import com.rede.didiok.admin.entity.AdminEntity;
import com.rede.didiok.admin.entity.SystemConfigEntity;
import com.rede.didiok.admin.service.AdminService;
import com.rede.didiok.admin.service.SysParamsService;
import com.rede.didiok.admin.service.SystemConfigService;
import com.rede.didiok.admin.utils.FileUtil;
import com.rede.didiok.common.constant.conf.MessageConf;
import com.rede.didiok.common.constant.conf.RedisConf;
import com.rede.didiok.common.constant.conf.SQLConf;
import com.rede.didiok.common.constant.conf.SysConf;
import com.rede.didiok.common.constant.global.Constants;
import com.rede.didiok.common.dto.admin.SystemConfigDto;
import com.rede.didiok.common.dto.file.PictureDto;
import com.rede.didiok.common.dto.rank.RankMemberDto;
import com.rede.didiok.common.dto.user.UserDto;
import com.rede.didiok.common.enums.*;
import com.rede.didiok.common.exception.exceptionType.FeignException;
import com.rede.didiok.common.exception.exceptionType.QueryException;
import com.rede.didiok.common.feign.CommunityFeignClient;
import com.rede.didiok.common.feign.FileFeignClient;
import com.rede.didiok.common.feign.RankFeignClient;
import com.rede.didiok.common.feign.UserFeignClient;
import com.rede.didiok.common.holder.RequestHolder;
import com.rede.didiok.common.utils.*;
import com.rede.didiok.common.utils.business.DomainEventUtil;
import com.rede.didiok.common.utils.business.RabbitMqUtil;

/**
 * @author 遇见
 */
@Service(value = "rankMemberSupport")
@Slf4j
public class RankMemberSupport {

    /**
     * 系统参数服务
     */
    @Resource
    private SysParamsService sysParamsService;
    /**
     * 系统参数服务
     */
    @Resource
    private SystemConfigService systemConfigService;

    /**
     * 榜单服务
     */
    @Resource
    RankFeignClient rankFeignClient;

    /**
     * 社区服务
     */
    @Resource
    CommunityFeignClient communityFeignClient;

    /**
     * 用户服务
     */
    @Resource
    private UserFeignClient userFeignClient;

    /**
     * 管理员服务
     */
    @Resource
    private AdminService adminService;

    @Resource
    private FileUtil fileUtil;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private RabbitMqUtil rabbitMqUtil;

    @Autowired
    FileFeignClient fileFeignClient;

    @Resource
    private BaiduSeoConfig baiduSeoConfig;

    /**
     * 领域事件工具类
     */
    @Resource
    private DomainEventUtil domainEventUtil;

    public String addRankMember(RankMemberDto rankMemberDto) {
        HttpServletRequest request = RequestHolder.getRequest();

        R countResulr = rankFeignClient.countRankMemberByLevel(rankMemberDto.getLevel());
        Integer count = countResulr.getData(new TypeReference<Integer>(){});
        // 判断插入博客的时候，会不会超过预期设置
        String addVerdictResult = addVerdict(count + 1, rankMemberDto.getLevel());
        // 判断是否能够添加推荐
        if (StringUtils.isNotBlank(addVerdictResult)) {
            return addVerdictResult;
        }
        // 当为后台管理员添加的时候
        AdminEntity admin = adminService.getById(request.getAttribute(SysConf.ADMIN_UID).toString());
        if (admin == null) {
            return ResultUtil.errorWithMessage("管理员状态错误,请重新登录后发布!");
        }
        // 判断是否附身用户
        if (StringUtils.isEmpty(admin.getUserUid())) {
            return ResultUtil.errorWithMessage("您暂未附身用户，无法发表文章，请到 管理员管理-> 编辑, 选择要附身用户 再重新发表");
        }

        if (admin != null) {
            // 判断该管理员是否进行了权限附身
            Boolean isUserOp = false;
            if (StringUtils.isNotEmpty(admin.getUserUid())) {
                R result = userFeignClient.getUserById(admin.getUserUid());
                UserDto user;
                if(result.getCode()==0){
                    user = result.getData(new TypeReference<UserDto>(){});
                }else {
                    // 获取异常信息
                    throw new FeignException("feign调用异常（根据用户id找用户）：失败");
                }
                if (user != null) {

                    rankMemberDto.setCreateUserUid(user.getUid());
                    rankMemberDto.setUser(user);
                    // 被权限附身的管理员，改成以用户投稿的方式上传文章
                    rankMemberDto.setRankMemberSource(ContributeSourceEnum.USER_PUBLISH);
                }
            }

        }

        /**
         * 管理员新增无需审核 且自动发布
         */
        rankMemberDto.setAuditStatus(AuditStatusEnum.AGREE);
        rankMemberDto.setAuditTime(new Date());
        rankMemberDto.setIsPublish(PublishEnum.PUBLISH);

        this.setRankMember(rankMemberDto);
        // 调用feign接口保存、发布新增领域事件
        rankFeignClient.addRankMemberByAdmin(rankMemberDto);

        return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS);
    }

    /**
     * 获取博客列表
     * @param rankMemberDto
     * @return
     */
    public IPage<RankMemberDto> getRankMemberPageList(RankMemberDto rankMemberDto) {
        R result = rankFeignClient.getRankMemberPageList(rankMemberDto);
        IPage<RankMemberDto> pageList = null;
        if(result.getCode() == 0){
            pageList = result.getData(new TypeReference<IPage<RankMemberDto>>(){});
        }else{
            throw new FeignException("feign调用异常（获取榜单成员列表）：失败");
        }
        if(null == pageList){
            return null;
        }
        List<RankMemberDto> list = pageList.getRecords();

        final StringBuffer fileUids = new StringBuffer();

        List<String> rankMemberUids = new ArrayList<>();
        List<String> userUids = new ArrayList<>();
        list.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getFileUid())) {
                fileUids.append(item.getFileUid() + SysConf.FILE_SEGMENTATION);
            }

            userUids.add(item.getCreateUserUid());
            rankMemberUids.add(item.getUid());
        });

        String pictureList = null;
        if (fileUids != null) {
            pictureList = fileFeignClient.getPicture(fileUids.toString(), SysConf.FILE_SEGMENTATION);
        }

        List<Map<String, Object>> picList = fileUtil.getPictureMap(pictureList);

        Map<String, String> pictureMap = new HashMap<>();
        R userMapResult= userFeignClient.getUserAvatarMapByIds(userUids);
        Map<String, UserDto> userMap = null;
        if (userMapResult.getCode() == 0) {
            userMap = userMapResult.getData(new TypeReference<Map<String, UserDto>>(){});
        }else {
            throw new FeignException("feign调用异常（获取带头像的用户Map）：失败");
        }


        picList.forEach(item -> {
            pictureMap.put(item.get(SQLConf.UID).toString(), item.get(SQLConf.URL).toString());
        });

        for (RankMemberDto item : list) {

            //获取图片
            if (StringUtils.isNotEmpty(item.getFileUid())) {
                List<String> pictureUidsTemp = StringUtils.changeStringToString(item.getFileUid(), SysConf.FILE_SEGMENTATION);
                List<String> pictureListTemp = new ArrayList<>();

                pictureUidsTemp.forEach(picture -> {
                    pictureListTemp.add(pictureMap.get(picture));
                });
                item.setPhotoList(pictureListTemp);
            }
            item.setUser(userMap.get(item.getCreateUserUid()));
        }
        pageList.setRecords(list);
        return pageList;
    }


    /**
     * 设置博客的分类标签和内容
     *
     * @param
     * @return
     */
    private RankMemberDto setRankMember(RankMemberDto rankMemberDto) {
        String fileUid = rankMemberDto.getFileUid();
        String userUid = rankMemberDto.getCreateUserUid();
        String adminUid = rankMemberDto.getAdminUid();

        //获取图片
        if (StringUtils.isNotEmpty(fileUid)) {
            // 获取图片Map集合
            Map<String, String> pictureMap = fileUtil.fileUidToFileUrlMap(Collections.singletonList(fileUid));
            List<String> pictureUidsTemp = StringUtils.changeStringToString(fileUid, SysConf.FILE_SEGMENTATION);
            List<String> pictureListTemp = new ArrayList<>();

            pictureUidsTemp.forEach(picture -> {
                pictureListTemp.add(pictureMap.get(picture));
            });
            rankMemberDto.setPhotoList(pictureListTemp);
        }

        // 判断用户投稿，还是后台管理员添加
        if (ContributeSourceEnum.USER_PUBLISH.equals(rankMemberDto.getRankMemberSource())) {

            if (StringUtils.isNotEmpty(userUid)) {
                // 获取用户信息
                R userResult = userFeignClient.getUserById(userUid);
                if(userResult.getCode()==0){
                    UserDto userDto = userResult.getData(new TypeReference<UserDto>(){});
                    rankMemberDto.setUser(userDto);
                }else {
                    // 获取异常信息
                    String msg = userResult.getData("msg",new TypeReference<String>(){});
                    throw new FeignException("feign调用异常（根据用户id找用户）："+msg);
                }
            }
        } else {
            if (StringUtils.isNotEmpty(adminUid)) {
                AdminEntity adminEntity = adminService.getById(adminUid);
                UserDto user = new UserDto();

                if (adminEntity != null) {
                    user.setAvatar(adminEntity.getAvatar());
                    user.setUid(adminEntity.getUid());
                    user.setOccupation(adminEntity.getOccupation());
                    user.setGender(adminEntity.getGender());
                    user.setSummary(adminEntity.getSummary());
                    user.setNickname(adminEntity.getNickname());
                    user.setPhotoUrl(adminEntity.getPhotoUrl());
                    rankMemberDto.setUser(user);
                }
            }
        }

        return rankMemberDto;
    }


    public String uploadLocalRankMember(List<MultipartFile> filedatas) {
        // 获取当前管理员
        AdminEntity admin = adminService.getMe();

        // 判断是否附身用户
        if (StringUtils.isEmpty(admin.getUserUid())) {
            return ResultUtil.errorWithMessage("您暂未附身门户用户，无法发表文章，请到 管理员管理-> 编辑, 选择要附身用户 再重新发表");
        }
        SystemConfigEntity systemConfig = systemConfigService.getOneSystemConfig();
        if (systemConfig == null) {
            return ResultUtil.errorWithMessage(MessageConf.SYSTEM_CONFIG_NOT_EXIST);
        } else {
            if (OpenStatusEnum.OPEN.equals(systemConfig.getUploadQiNiu()) && (StringUtils.isEmpty(systemConfig.getQiNiuPictureBaseUrl()) || StringUtils.isEmpty(systemConfig.getQiNiuAccessKey())
                    || StringUtils.isEmpty(systemConfig.getQiNiuSecretKey()) || StringUtils.isEmpty(systemConfig.getQiNiuBucket()) || StringUtils.isEmpty(systemConfig.getQiNiuArea()))) {
                return ResultUtil.errorWithMessage(MessageConf.PLEASE_SET_QI_NIU);
            }

            if (OpenStatusEnum.OPEN.equals(systemConfig.getUploadLocal()) && StringUtils.isEmpty(systemConfig.getLocalPictureBaseUrl())) {
                return ResultUtil.errorWithMessage(MessageConf.PLEASE_SET_LOCAL);
            }
        }

        List<MultipartFile> fileList = new ArrayList<>();
        List<String> fileNameList = new ArrayList<>();
        for (MultipartFile file : filedatas) {
            String fileOriginalName = file.getOriginalFilename();
            if (FileUtils.isMarkdown(fileOriginalName)) {
                fileList.add(file);
                // 获取文件名
                fileNameList.add(FileUtils.getFileName(fileOriginalName));
            } else {
                return ResultUtil.errorWithMessage("目前仅支持Markdown文件");
            }
        }

        if (fileList.size() == 0) {
            return ResultUtil.errorWithMessage("请选中需要上传的文件");
        }

        // 文档解析
        List<String> fileContentList = new ArrayList<>();
        for (MultipartFile multipartFile : fileList) {
            try {
                Reader reader = new InputStreamReader(multipartFile.getInputStream(), StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(reader);
                String line;
                StringBuilder content = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    content.append(line).append("\n");
                }
                // 将Markdown转换成html
                String blogContent = FileUtils.markdownToHtml(content.toString());
                fileContentList.add(blogContent);
            } catch (Exception e) {
                log.error("文件解析出错");
                log.error(e.getMessage());
            }
        }

        HttpServletRequest request = RequestHolder.getRequest();
        String pictureList = request.getParameter(SysConf.PICTURE_LIST);
        List<LinkedTreeMap<String, String>> list = (List<LinkedTreeMap<String, String>>) JsonUtils.jsonArrayToArrayList(pictureList);
        Map<String, String> pictureMap = new HashMap<>();
        for (LinkedTreeMap<String, String> item : list) {

            if (FilePriorityEnum.QI_NIU.equals(systemConfig.getContentPicturePriority())) {
                // 获取七牛云上的图片
                pictureMap.put(item.get(SysConf.FILE_OLD_NAME), item.get(SysConf.QI_NIU_URL));
            } else if (FilePriorityEnum.LOCAL.equals(systemConfig.getContentPicturePriority())) {
                // 获取本地的图片
                pictureMap.put(item.get(SysConf.FILE_OLD_NAME), item.get(SysConf.PIC_URL));
            } else if (FilePriorityEnum.MINIO.equals(systemConfig.getContentPicturePriority())) {
                // 获取MINIO的图片
                pictureMap.put(item.get(SysConf.FILE_OLD_NAME), item.get(SysConf.MINIO_URL));
            }
        }
        // 需要替换的图片Map
        Map<String, String> matchUrlMap = new HashMap<>();
        for (String blogContent : fileContentList) {
            List<String> matchList = RegexUtils.match(blogContent, "<img\\s+(?:[^>]*)src\\s*=\\s*([^>]+)>");
            for (String matchStr : matchList) {
                String[] splitList = matchStr.split("\"");
                // 取出中间的图片
                if (splitList.length >= 5) {
                    // alt 和 src的先后顺序
                    // 得到具体的图片路径
                    String pictureUrl = "";
                    if (matchStr.indexOf("alt") > matchStr.indexOf("src")) {
                        pictureUrl = splitList[1];
                    } else {
                        pictureUrl = splitList[3];
                    }

                    // 判断是网络图片还是本地图片
                    if (!pictureUrl.startsWith(SysConf.HTTP)) {
                        // 那么就需要遍历全部的map和他匹配
                        for (Map.Entry<String, String> map : pictureMap.entrySet()) {
                            // 查看Map中的图片是否在需要替换的key中
                            if (pictureUrl.indexOf(map.getKey()) > -1) {
                                if (FilePriorityEnum.QI_NIU.equals(systemConfig.getContentPicturePriority())) {
                                    // 获取七牛云上的图片
                                    matchUrlMap.put(pictureUrl, systemConfig.getQiNiuPictureBaseUrl() + map.getValue());
                                } else if (FilePriorityEnum.LOCAL.equals(systemConfig.getContentPicturePriority())) {
                                    // 获取本地的图片
                                    matchUrlMap.put(pictureUrl, systemConfig.getLocalPictureBaseUrl() + map.getValue());
                                } else if (FilePriorityEnum.MINIO.equals(systemConfig.getContentPicturePriority())) {
                                    // 获取MINIO的图片
                                    matchUrlMap.put(pictureUrl, systemConfig.getMinioPictureBaseUrl() + map.getValue());
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }

        // 获取任意博客封面
        R pictureResult = fileFeignClient.getTopOne();
        PictureDto pictureDto;
        if(pictureResult.getCode() == 0){
            pictureDto = pictureResult.getData(new TypeReference<PictureDto>(){});
        }else {
            throw new FeignException("feign调用异常（获取任意博客封面）：失败");
        }
        if (pictureDto == null) {
            return ResultUtil.errorWithMessage("使用本地上传，请先确保榜单成员图片中含有数据");
        }
        // 存储需要上传的博客
        List<RankMemberDto> rankMemberDtoList = new ArrayList<>();
        // 开始进行图片替换操作
        Integer count = 0;


        // 判断该管理员是否进行了权限附身
        Boolean isUserOp = false;
        UserDto user = null;
        if (StringUtils.isNotEmpty(admin.getUid())) {
            R result = userFeignClient.getUserById(admin.getUserUid());
            if(result.getCode()==0){
                user = result.getData(new TypeReference<UserDto>(){});
            }else {
                throw new FeignException("feign调用异常（根据用户id找用户）：失败");
            }
            if (user != null) {
                isUserOp = true;
            }
        }

        for (String content : fileContentList) {
            // 循环替换里面的图片
            for (Map.Entry<String, String> map : matchUrlMap.entrySet()) {
                content = content.replace(map.getKey(), map.getValue());
            }
            RankMemberDto memberDto = new RankMemberDto();
//            memberDto.setCatUid(r.getUid());
//            memberDto.setGradeUid(memberGradeEntity.getUid());
            memberDto.setAdminUid(admin.getUid());
            memberDto.setLevel(LevelEnum.NORMAL);
            memberDto.setMemberName(fileNameList.get(count));

            if (user != null) {
                memberDto.setCreateUserName(user.getNickname());
                memberDto.setCreateUserUid(user.getUid());
                // 被权限附身的管理员，改成以用户投稿的方式上传文章
                memberDto.setRankMemberSource(ContributeSourceEnum.USER_PUBLISH);
                isUserOp = true;
            } else {
                memberDto.setRankMemberSource(ContributeSourceEnum.ADMIN_PUBLISH);
            }
            if (!isUserOp) {
                if (StringUtils.isNotEmpty(admin.getNickname())) {
                    memberDto.setCreateUserName(admin.getNickname());
                } else {
                    memberDto.setCreateUserName(admin.getUserName());
                }
            }
            // 后端上架，自动审批完成
            memberDto.setAuditStatus(AuditStatusEnum.AGREE);
            // 默认开启加载校验
            memberDto.setOpenLoadingValid(Integer.valueOf(OpenStatusEnum.OPEN));

            // 设置简介
            String summary = StringUtils.dealContent(content);
            if (summary.length() < 190) {
                memberDto.setSummary(summary);
            } else {
                memberDto.setSummary(summary.substring(0, 190) + "...");
            }
//            memberDto.setContent(content);
            memberDto.setFileUid(pictureDto.getFileUid());
//            memberDto.setIsOriginal(EOriginal.ORIGINAL);
            memberDto.setIsPublish(PublishEnum.NO_PUBLISH);
            memberDto.setOpenComment(Integer.valueOf(OpenStatusEnum.OPEN));
            memberDto.setContent(content);
            rankMemberDtoList.add(memberDto);

            count++;

        }

        /////
        return rankFeignClient.uploadLocalRankMember(rankMemberDtoList);

    }


    public String editRankMember(RankMemberDto rankMemberDto) {

        HttpServletRequest request = RequestHolder.getRequest();
        rankMemberDto.setAdminUid(request.getAttribute(SysConf.ADMIN_UID).toString());

        Integer level = rankMemberDto.getLevel();
        // 当前等级最大允许榜单成员的数量
        Long currentLevelAllowCount = null;
                //添加的时候进行判断
        switch (level) {
            case LevelEnum.FIRST: {
                currentLevelAllowCount = Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.RANK_MEMBER_FIRST_COUNT));

            }
            break;

            case LevelEnum.SECOND: {
                currentLevelAllowCount = Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.RANK_MEMBER_SECOND_COUNT));

            }
            break;

            case LevelEnum.THIRD: {
                currentLevelAllowCount = Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.RANK_MEMBER_THIRD_COUNT));

            }
            break;

            case LevelEnum.FOURTH: {
                currentLevelAllowCount = Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.RANK_MEMBER_FOURTH_COUNT));

            }
            break;
            default: {

            }
        }
        rankMemberDto.setCurrentLevelAllowCount(currentLevelAllowCount);

        // 编辑榜单成员
        return rankFeignClient.editRankMemberByAdmin(rankMemberDto);

    }

    public String updateLevel(RankMemberDto rankMemberDto) {

        HttpServletRequest request = RequestHolder.getRequest();
        rankMemberDto.setAdminUid(request.getAttribute(SysConf.ADMIN_UID).toString());

        Integer level = rankMemberDto.getLevel();
        // 当前等级最大允许榜单成员的数量
        Long currentLevelAllowCount = null;
        //添加的时候进行判断
        switch (level) {
            case LevelEnum.FIRST: {
                currentLevelAllowCount = Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.RANK_MEMBER_FIRST_COUNT));

            }
            break;

            case LevelEnum.SECOND: {
                currentLevelAllowCount = Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.RANK_MEMBER_SECOND_COUNT));

            }
            break;

            case LevelEnum.THIRD: {
                currentLevelAllowCount = Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.RANK_MEMBER_THIRD_COUNT));

            }
            break;

            case LevelEnum.FOURTH: {
                currentLevelAllowCount = Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.RANK_MEMBER_FOURTH_COUNT));

            }
            break;
            default: {

            }
        }
        rankMemberDto.setCurrentLevelAllowCount(currentLevelAllowCount);

        // 编辑榜单成员
        return rankFeignClient.updateRankMemberLevel(rankMemberDto);

    }


    /**
     * 添加时校验
     *
     * @param count
     * @param level
     * @return
     */
    private String addVerdict(Integer count, Integer level) {

        //添加的时候进行判断
        switch (level) {
            case LevelEnum.FIRST: {
                Long rankMemberFirstCount = Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.RANK_MEMBER_FIRST_COUNT));
                if (count > rankMemberFirstCount) {
                    return ResultUtil.errorWithMessage("一级推荐不能超过" + rankMemberFirstCount + "个");
                }
            }
            break;

            case LevelEnum.SECOND: {
                Long rankMemberSecondCount = Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.RANK_MEMBER_SECOND_COUNT));
                if (count > rankMemberSecondCount) {
                    return ResultUtil.errorWithMessage("二级推荐不能超过" + rankMemberSecondCount + "个");
                }
            }
            break;

            case LevelEnum.THIRD: {
                Long rankMemberThirdCount = Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.RANK_MEMBER_THIRD_COUNT));
                if (count > rankMemberThirdCount) {
                    return ResultUtil.errorWithMessage("三级推荐不能超过" + rankMemberThirdCount + "个");
                }
            }
            break;

            case LevelEnum.FOURTH: {
                Long rankMemberFourthCount = Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.RANK_MEMBER_FOURTH_COUNT));
                if (count > rankMemberFourthCount) {
                    return ResultUtil.errorWithMessage("四级推荐不能超过" + rankMemberFourthCount + "个");
                }
            }
            break;
            default: {

            }
        }
        return null;
    }


    public String auditRankMember(RankMemberDto rankMemberDto) {
        String nickname = adminService.getNicknameById(RequestHolder.getAdminUid());
        rankMemberDto.setAuditName(nickname);
        return rankFeignClient.auditRankMember(rankMemberDto);

    }


    public String batchAuditRankMember(List<RankMemberDto> rankMemberDtoList) {
        if (rankMemberDtoList.size() <= 0) {
            return ResultUtil.errorWithMessage(MessageConf.PARAM_INCORRECT);
        }
        String nickname = adminService.getNicknameById(RequestHolder.getAdminUid());

        List<String> uidList = rankMemberDtoList.stream().map(RankMemberDto::getUid).collect(Collectors.toList());
        String auditStatus = String.valueOf(rankMemberDtoList.get(0).getAuditStatus());
        String rejectReason = rankMemberDtoList.get(0).getRejectReason();
        rankMemberDtoList.forEach(item->{
            item.setAuditName(nickname);
        });

        /**
         * 获取审核博客列表中
         */
        Set<String> userUids = rankMemberDtoList.stream().map(item -> item.getCreateUserUid()).collect(Collectors.toSet());
        /**
         * 查询这些博客博主中开启了通知且邮箱不为空的博主
         */
        // 根据userUids 获取 开启邮件通知 的用户
        R result = userFeignClient.listUserStartEmailNotification(userUids);
        List<UserDto> userList = new ArrayList<>();
        if (result.getCode() == 0) {
            userList = result.getData(new TypeReference<List<UserDto>>(){});
        }

        if (!userList.isEmpty()) {

            userList.forEach(user -> {
                AtomicReference<Integer> index = new AtomicReference<>(0);
                List<RankMemberDto> ownRankMemberList = rankMemberDtoList.stream().filter(item -> {
                    return item.getCreateUserUid().equals(user.getUid());
                }).collect(Collectors.toList());
                StringBuilder text = new StringBuilder();
                text.append(String.format("<p>可爱的博主%s,您的榜单成员稿件</p>", user.getNickname()));
                ownRankMemberList.forEach(item -> {
                    index.getAndSet(index.get() + 1);
                    String message = "";
                    if (AuditStatusEnum.REJECT.equals(item.getAuditStatus())) {
                        message = "审核未通过,审核原因为" + item.getRejectReason();
                    }
                    if (AuditStatusEnum.AGREE.equals(item.getAuditStatus())) {
                        message = "审核已通过";
                    }
                    text.append(String.format("\n<p>%s.%s%s</p>", index.get(), item.getMemberName(), message));
                });
                rabbitMqUtil.sendSimpleEmail(user.getEmail(), text.toString());
            });
        }

        ////

        return rankFeignClient.batchAuditRankMember(uidList, nickname, auditStatus, rejectReason);

    }

    /**
     * 推送选择榜单成员
     * @param rankMemberDtoList
     * @return
     */
    public String pushBatch(List<RankMemberDto> rankMemberDtoList) {


        String Site = baiduSeoConfig.getSite();
        String Token = baiduSeoConfig.getToken();
        StringBuilder res = new StringBuilder();
        List<String> memberUids = rankMemberDtoList.stream().map(RankMemberDto::getUid).collect(Collectors.toList());

        R result = rankFeignClient.listRankMemberByUidList(memberUids);
        if(result.getCode() == 0){
            List<RankMemberDto> memberList = result.getData(new TypeReference<List<RankMemberDto>>(){});
            Map<String, RankMemberDto> memberMap = memberList.stream().collect(Collectors.toMap(RankMemberDto::getUid, Function.identity(), (oldValue, newValue) -> newValue));
            rankMemberDtoList.forEach(item -> {
                RankMemberDto rankMemberDto = memberMap.get(item.getUid());
                if (res.toString().equals("")) {
                    res.append(Site + "/info/" + rankMemberDto.getOid());
                } else {
                    res.append(Constants.SYMBOL_COMMA).append(Site + "/info/" + rankMemberDto.getOid());
                }
            });
            String[] urls = res.toString().split(Constants.SYMBOL_COMMA);

            //将urlsArr数组转化为字符串形式
            String urlsStr = baiduSeoConfig.urlsArrToString(urls);
            //打印结果
            String resStr = baiduSeoConfig.Post(Site, Token, urlsStr);
            return resStr;
        }else {
            throw new FeignException("feign调用异常（根据id列表获取榜单成员列表）：失败");
        }

    }

    /**
     * 批量同步榜单成员索引
     * @return
     */
    public String initRankMemberElasticIndex(ResourceTypeEnum resourceType) {
        String result = "";

        // 从Redis中获取系统配置
        String systemConfigJson = redisUtil.get(RedisConf.SYSTEM_CONFIG);
        if (StringUtils.isEmpty(systemConfigJson)) {
            QueryWrapper<SystemConfigEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
            SystemConfigEntity systemConfig = systemConfigService.getOne(queryWrapper);
            if (systemConfig == null) {
                throw new QueryException(MessageConf.SYSTEM_CONFIG_IS_NOT_EXIST);
            } else {
                // 将系统配置存入Redis中【设置过期时间24小时】
                SystemConfigDto systemConfigDto = new SystemConfigDto();
                BeanUtils.copyProperties(systemConfig, systemConfigDto);
                redisUtil.setEx(RedisConf.SYSTEM_CONFIG, JsonUtils.objectToJson(systemConfigDto), 24, TimeUnit.HOURS);
            }
        }
        switch (resourceType) {
            case RANK_MEMBER: {
                result = rankFeignClient.buildRankMemberAggDoc();
            }
            break;

            case MOMENT: {
                result = communityFeignClient.buildMomentAggDoc();
            }
            break;

            default:
                return ResultUtil.errorWithMessage("请输入正确的参数");
        }

        return ResultUtil.successWithMessage(result);
    }
}
